package grpc

import (
	"TOScheduler/src/pb"
	"context"
	"google.golang.org/grpc"
	"strconv"
)

var (
	client pb.SendMsgTSTDClient
)

func InitTDClient(tdSocket string) {
	conn, err := grpc.Dial(tdSocket, grpc.WithInsecure())
	if err != nil {
		log.Fatalf("[gRPC TS->TD] error ( %s ): %s", tdSocket, err)
	}
	client = pb.NewSendMsgTSTDClient(conn)
	log.Infof("[gRPC TS->TD] successfully connected to %s", tdSocket)
}

func SendProfileTSTD(brief *pb.ToTOBrief) {
	// set the request message
	res := pb.ToTD{
		Basic:   brief.Basic,
		Latency: brief.Latency,
	}
	id, _ := strconv.Atoi(brief.Basic[0].Id[:13])
	r, err := client.SendMsgTSTD(context.Background(), &res)
	if err != nil {
		// latch work
		log.Warnf("[gRPC TS->TD] error, execute locally: %v", err)
		for _, b := range brief.Basic {
			b.OffloadTo = b.ArriveAt
		}
		// chBrief <- brief
		briefMap.Store(id, brief)
	} else {
		briefMap.Store(id, &pb.ToTOBrief{Basic: r.Basic, Latency: r.Latency})
	}
	chFlag1 <- id
}
